﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace IBNet.DayTrade
{
   static class DayTradeProgram
   {
      // OCA (one cancels all) numbers are stored to a file between program runs
      // because TWS requires OCA group strings to be unique.
      // For example, when trading MSFT and the value in 
      // ..\\..\\..\\DayTradeOcaNumber.txt is "1",
      // the OCA groups for the first three trades with MSFT will be
      // MSFT1, MSFT2, and MSFT3. Upon closing DayTrade.exe, "3" is written to
      // ..\\..\\..\\DayTradeOcaNumber.txt. If DayTrade.exe is rerun
      // and GOOG is traded, the OCA group string will be GOOG4.
      private const string DayTradeOcaNumberFilepath = "..\\..\\..\\DayTradeOcaNumber.txt";
      public static int DaytradeOcaNumber;

      static void Main()
      {
         if (!File.Exists(DayTradeOcaNumberFilepath))
         {
            MessageBox.Show(DayTradeOcaNumberFilepath + " must exist to run this program. \r\nWhen creating DayTradeOcaNumber.txt for the first time its contents should be '1' on line 1.", 
               "Error: " + DayTradeOcaNumberFilepath + " must exist");
            Environment.Exit(1);
         }

         // Use mutex to allow only one instance of DayTrade.exe.
         bool successfullyAcquiredDayTradeMutex;
         using (Mutex dayTradeMutex = 
            new Mutex(true, "DayTrade.exe", out successfullyAcquiredDayTradeMutex))
         {
            if (successfullyAcquiredDayTradeMutex)
            {
               string ocaNumberAsString = File.ReadAllLines(DayTradeOcaNumberFilepath)[0];
               DaytradeOcaNumber = Int32.Parse(ocaNumberAsString);

               Application.EnableVisualStyles();
               Application.Run(DayTradeMainForm.MainForm);

               ocaNumberAsString = DaytradeOcaNumber.ToString();
               File.WriteAllText(DayTradeOcaNumberFilepath, ocaNumberAsString);
            }
            else
            {
               MessageBox.Show("Only one instance of DayTrade.exe can be running at a time.", "Error");
            }
         }
      }
   }
}